import { NextResponse } from 'next/server';
import User from '@/models/user';
import argon2 from 'argon2';

export async function GET() {
  try {
    const users = await User.findAll();
    return NextResponse.json({ code: 0, data: users, msg: '获取用户列表成功' });
  } catch (error) {
    console.error('获取用户列表失败:', error);
    return NextResponse.json({ code: 500, msg: '获取用户列表失败' }, { status: 500 });
  }
}

export async function POST(request: Request) {
  try {
    const data = await request.json();
    
    // 检查是否提供了密码（前端使用password_hash字段名）
    if (!data.password_hash) {
      return NextResponse.json({ code: 400, msg: '密码不能为空' }, { status: 400 });
    }
    
    // 对密码进行加密
    const hashedPassword = await argon2.hash(data.password_hash);
    
    // 创建用户对象，使用加密后的密码
    const userData = {
      username: data.username,
      password_hash: hashedPassword,
      email: data.email,
      created_at: new Date()
    };
    
    const user = await User.create(userData);
    return NextResponse.json({ code: 0, data: user, msg: '创建用户成功' }, { status: 201 });
  } catch (error) {
    console.error('创建用户失败:', error);
    return NextResponse.json({ code: 500, msg: '创建用户失败' }, { status: 500 });
  }
}